package co.fitstart.market.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.demo2do.core.BusinessException;
import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.support.Result;
import com.demo2do.core.support.handler.FileUploadHanlder;

import co.fitstart.entity.market.ParticipationQrcode;
import co.fitstart.entity.user.User;
import co.fitstart.market.service.QrcodeService;

@Service("qrcodeService")
public class QrcodeServiceImpl implements QrcodeService{
    
    @Value("#{ctx['system.host']}")
    private String path;
    
    @Autowired
    private FileUploadHanlder fileUploadHanlder;
    
    @Autowired
    private GenericDaoSupport genericDaoSupport;
    
    private static final Logger logger = LoggerFactory.getLogger(QrcodeServiceImpl.class);

    /*
     * (non-Javadoc)
     * @see co.fitstart.market.service.QrcodeService#generateQrcode(boolean, co.fitstart.entity.user.User)
     */
    public String generateQrcode(boolean signin, User user) {
        String qrcodeValue = path + "/participation/participate";
        if(signin) {
            qrcodeValue = qrcodeValue + "?recommender=" + user.getOpenid();
        } else {
            qrcodeValue = qrcodeValue + "?inviter=" + user.getOpenid();
        }
        
        logger.trace("generateQrcode qrcodeValue [{}]", qrcodeValue);
        Result result = fileUploadHanlder.generateQrCode(qrcodeValue);
        
        if(result.isValid()) {
            
            ParticipationQrcode participationQrcode = new ParticipationQrcode(result.getData().get("key").toString(), signin, user);
            genericDaoSupport.save(participationQrcode);
            
            return result.getData().get("key").toString();
        } else {
            throw new BusinessException("生成二维码失败");
        }
    }

}
